<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\services\order;

use app\common\AgentTool;
use app\common\InventoryTool;
use app\common\OrderTool;
use app\common\StoreSeckillTool;
use app\dao\activity\coupon\StoreCouponUserDao;
use app\kefuapi\controller\Order;
use app\model\agent\AgentLevel;
use app\model\order\OrderItems;
use app\model\order\Orders;
use app\model\product\sku\StoreProductStockRelation;
use app\model\user\User;
use app\model\order\StoreCart;
use app\model\order\StoreOrder;
use app\model\product\product\StoreProduct;
use app\model\product\sku\StoreProductAttrValue;
use app\model\user\UserAddress;
use app\services\BaseServices;
use app\services\product\product\StoreProductServices;
use Carbon\Carbon;
use crmeb\exceptions\ApiException;
use crmeb\exceptions\AdminException;
use crmeb\services\pay\Pay;
use think\facade\Db;
use think\facade\Config;

class OrderService extends BaseServices
{
    /**
     * @param $params
     * @return array
     * 订单地址列表
     */
    public function addressIndex($params)
    {
        return [];
    }


    public function getFinanceList($where)
    {
        $start_time = $where['start_time'] ?? null;
        $end_time = $where['end_time'] ?? null;
        $sn = $where['sn'] ?? '';
        $limit = $where['limit'] ?? 15;
        $orders = Orders::where('is_del', 0)->when(($start_time && $end_time), function ($query) use ($start_time, $end_time) {
            $query->where('add_time', '>', $start_time)->where('add_time', '<=', $end_time);
        })->when($sn, function ($query) use ($sn) {
            $query->where('sn', $sn);
        })->paginate($limit);

        $list = [];
        foreach ($orders as $order) {
            $list[] = [
                'trade_time'  => Carbon::parse($order->add_time)->format('Y-m-d H:i:s'),
                'order_type_text'   =>  '正常订单',
                'distributor_name'  =>  '平台',
                'sn'    =>  $order->sn,
                'price' =>  $order->price,
                'pay_price' =>  $order->price,
                'commission'    =>  '逻辑不确定',
                'distributor_price' =>  '逻辑不确定'
            ];
        }

        return [
            'count' =>  $orders->count(),
            'list'  =>  $list
        ];
    }



    /**
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 确认订单详情
     */
    public function info($params)
    {
        $orderTool = OrderTool::init();
        $orderTool->couponInit($params['user_id'], $params['cart_ids'],intval($params['coupon_id']));

        $address_info = (!empty($params['address_id'])) ?
            UserAddress::where('uid', $params['user_id'])->where('id', $params['address_id'])->where('is_del', 0)->find()
            : UserAddress::where('uid', $params['user_id'])->where('is_default', 1)->where('is_del', 0)->find();

        $result = [
            'address_info'  =>  $address_info ?? [],
            'cart_info' =>  $orderTool->getCartInfo($params['user_id'], $params['cart_ids'], intval($params['coupon_id'])),
            'coupon_price' =>  $orderTool->couponPrice,
            'shipping_price' =>  $orderTool->shippingPrice,
            'fact_price' =>  bcsub($orderTool->totalPrice, $orderTool->couponPrice, 2),
            'seckill_price' =>  '待完善',
            'total_price' => $orderTool->totalPrice,
            'coupon_id' => $orderTool->couponId,
        ];

        return $result;
    }

    public function orderDetail($params){
        $result = Orders::with(['orderItems'])->find($params['order_id'])->toArray();
        $buyer = User::find($result['uid']);
        $result['buyer_phone'] = $buyer->phone;
        $orderItems = [];
        $result['total_price'] = $result['shipping_price'] = $result['reduce_price'] = 0;
        foreach ($result['orderItems'] as $orKey => $orVal) {
            $productRow = StoreProduct::where('id', $orVal['product_id'])->find();
            if(empty($productRow)) continue;
            $productAttrValueRow = StoreProductAttrValue::where([
                ['product_id', '=', $orVal['product_id']],
                ['unique', '=', $orVal['product_attr_value_unique']],
            ])->find();
            $result['distributor'] = '官方经销商';
            $result['sender'] = '';
            $result['total_price'] += $orVal['total_price'];
            $result['shipping_price'] += $orVal['shipping_price'];
            $result['reduce_price'] += $orVal['reduce_price'];
            $orderItems[] = [
                'id' => $orVal['id'],
                'total_price' => $orVal['total_price'],
                'fact_price' => $orVal['fact_price'],
                'real_pay' => $orVal['total_price'] - $orVal['reduce_price'],
                'nums' => $orVal['nums'],
                'remark' => $orVal['remark'],
                'store_name' => $productRow->store_name,
                'image' => $productAttrValueRow->image,
                'product_attr_value_unique' => $orVal['product_attr_value_unique'],
                'suk' => $productAttrValueRow->suk,
                'shipping_code' => $orVal['shipping_code'],
                'is_free' => $orVal['free_rule_uniques'] ? 1 : 0,
                'shipping_time' => $orVal['shipping_time'] ? date('Y-m-d H:i:s',$orVal['shipping_time']) : '',
                'coupon_detail' => ''
            ];
        }
        unset($result['orderItems']);
        $result['products'] = $orderItems;
        $result['add_time'] = date('Y-m-d H:i:s',$result['add_time']);
        $result['status_name'] = Orders::ORDER_STATUS_NAME[$result['status']];
        return $result;
    }


    /**
     * 创建订单
     * @param $params
     * @return int
     */
    public function create($params)
    {
         return Db::transaction(function () use ($params) {
            //地址
            $orderTool = OrderTool::init();
            $addressRow = $orderTool->defaultAddress($params['user_id'], ['*'], $params['address_id']);
            //购物车商品
            $totalNum = 0;
            $productPrice = $shippingPrice = $couponPrice =  0.00;
            $orderStoreCard = $orderTool->getOrderStoreCard($params['cart_ids'], $params['user_id']);

            $skill_ids = [];
            //优惠券
            $orderTool->couponInit($params['user_id'],$params['cart_ids'],$params['coupon_id']);
            $couponPrice = $orderTool->couponPrice;
            foreach($orderStoreCard as $val) {
                //判断满赠
                if($val['free_rule_id'] && $val['free_json']) {
                    OrderTool::init()->checkFreeRule($val['free_json']);
                    if($val['status'] == 0) {
                        throw new ApiException(31008);
                    }
                }

                //判断秒杀
                if($val['seckill_product_relation_id']) {
                    OrderTool::init()->checkSeckillProduct($val['seckillProduct']);
                    $skill_ids[$val['id']] = $val['seckillProduct']['seckill_id'];
                }

                //商品属性金额
                $price = $val['attrInfo']['price'];
                $seckillPrice = $val['seckillProduct']['activity_price'] ?? 0.00;

                $productPrice += $seckillPrice ? $seckillPrice * $val['cart_num'] : $price * $val['cart_num'];

                //重量和运费
                $weight = OrderTool::init()->getOrderWeightByCart($val);
                if (!isset($addressRow['city_id'])) {
                    throw new ApiException(31021);
                }
                $shippingPrice += (app()->make(StoreOrderServices::class))->getShippingPrice($addressRow['city_id'], $val['product_id'], $weight, $val['cart_num'], $val['free_rule_uniques'], $val['seckill_product_relation_id'], 0);
            }
            $totalPrice = $productPrice + $shippingPrice - $couponPrice;

            if(bcsub($totalPrice, $params['fact_price']) != 0) {
                throw new ApiException(31012);
            }

            //创建订单
            $orderData = [
                'sn'  =>  OrderTool::init()->getOrderSn(),
                'real_name' => $addressRow['real_name'],
                'user_phone' => $addressRow['phone'],
                'user_address' => $addressRow['province'] . ' ' . $addressRow['city'] . ' ' . $addressRow['district'] . ' ' . $addressRow['detail'],
                'total_num' => $totalNum,
                'remark' => htmlspecialchars($params['remark']),
                'uid'   =>  $params['user_id'],
                'price'   =>  $totalPrice,
                'add_time'  =>  time(),
                'province'  =>  $addressRow['province'],
                'city'  =>  $addressRow['city'],
                'district'  =>  $addressRow['district'],
                'city_id'   =>  $addressRow['city_id'],
                'coupon_id' => $orderTool->couponId,
            ];
            $orderId = Orders::insertGetId($orderData);
            if(!$orderId) {
                throw new ApiException(410200);
            }
            //创建订单子表数据
            $orderItemsData = [];
            foreach($params['cart_ids'] as $key => $val) {
                $storeCartRow = StoreCart::with(['attrInfo', 'productInfo'])->where('id', $val)->find();
                //重量和运费
                $weight = OrderTool::init()->getOrderWeightByCart($val);
                $shippingPrice = (app()->make(StoreOrderServices::class))->getShippingPrice($addressRow['city_id'], $storeCartRow->product_id, $weight, $storeCartRow->cart_num, $storeCartRow->free_rule_uniques, $storeCartRow->seckill_product_relation_id, 0);

                $productPrice = $storeCartRow->attrInfo ? $storeCartRow->attrInfo->price * $storeCartRow->cart_num : 0;
                // 查找是不是秒杀商品
                $seckillPrice = $storeCartRow->seckillProduct ? $storeCartRow->seckillProduct->activity_price : 0;
                $seckillReducePrice = $seckillPrice ? ($storeCartRow->attrInfo->price - $seckillPrice) * $storeCartRow->cart_num : 0;

                $couponPrice = 0;
                //数量
                $orderItemsData[] = [
                    'order_id' => $orderId,
                    'cart_id' => $val,
                    'uid' => $params['user_id'],
                    'product_id' => $storeCartRow->product_id ?? 0,
                    'product_attr_value_unique' => $storeCartRow->product_attr_unique ?? '',
                    'total_price' => $totalPrice,
                    'shipping_price' => $shippingPrice,
                    'reduce_price' => $seckillReducePrice + $couponPrice,
                    'fact_price' => $productPrice - $seckillReducePrice - $couponPrice + $shippingPrice,
                    'free_rule_uniques' => $storeCartRow->free_rule_uniques,
                    'nums' => $storeCartRow->cart_num, // 未包含赠品个数, 主要是用来计算营销活动库存计算
                    'seckill_id' => $skill_ids[$val] ?? 0,
                    'has_deal_stock'    =>  (isset($storeCartRow['productInfo']['store_type'])) ? ($storeCartRow['productInfo']['store_type'] == 1 ? 1 : 0 ) : 0,// 如果商品是
                    'free_json' =>  $storeCartRow['free_json'] ?? null
                ];
                if($orderTool->couponId > 0){//核销优惠券
                    app()->make(StoreCouponUserDao::class)->UserUseCoupon($orderTool->couponId,$params['user_id']);
                }

                //库存扣减
                InventoryTool::init()->inventory(request()->action(), $storeCartRow->product_id ?? 0, $storeCartRow->product_attr_unique ?? '', $storeCartRow->nums);
            }

            OrderItems::insertAll($orderItemsData);





             // 删除购物车状态
            StoreCart::whereIn('id', $params['cart_ids'])->update([
                'is_del'    =>  1,
            ]);

            return $orderId;
        });
    }

    /**
     * @param $params
     * @return void
     * 再次下单
     */
    public function again($params)
    {
        Db::transaction(function () use ($params) {
            //
        });
    }

    /**
     * @param $params
     * @return void
     * 订单支付
     */
    public function pay($params)
    {
        if(empty($params['bank_code'])){
            throw new ApiException(60006);
        }
        //修改订单状态为已支付
        $orderRow = OrderTool::init()->getOrder($params['order_id'], $params['user_id']);
        if(empty($orderRow)) {
            throw new ApiException(410173);
        }
        if($orderRow['pay_status'] == 1) {
            throw new ApiException(410174);
        }
        //更新支付方式
        Orders::where('id', $params['order_id'])->update(['pay_type' => $this->getPayTypeByCode($params['bank_code'])]);
        /**
         * 测试支付用 正式支付请删除
         */
        $this->paySuccess(['order_id'=>$params['order_id'],'user_id'=>$params['user_id'],'pay_sn'=>md5(uniqid('', true))]);

        $pay = app()->make(Pay::class, ['quickn_pay']);
        return $pay->create($orderRow['sn'], $orderRow['price'], '', '', '',['bank_code' => $params['bank_code']]);


//            OrderTool::init()->orderPay($params['order_id'], $params['user_id']);
//            //加入分销
//            AgentTool::init()->agent(request()->action(), $params['order_id'], $params['user_id']);
            //修改库存
//            InventoryTool::init()->outbound();

    }

    public function getPayTypeByCode($code){
        $pay_type_list = Config::get('pay.payList');
        foreach($pay_type_list as $k=>$val){
            if($val['bank_code'] == $code){
                return $k + 1;
            }
        }

    }

    /**
     * @param $params
     * @return array
     * 订单列表
     */
    public function index($params)
    {

        $listParams = [];
        $listParams['where'][] = ['uid', '=', $params['user_id']];
        $listParams['where'][] = ['is_del', '=', 0];
        // 如果前端传递 -1, 则标识搜索全部，此时需要特殊处理
        if(isset($params['status']) && $params['status'] != -1) {
            if ($params['status'] == 2) {
                $listParams['where_in']['status'] = [1, 2];
            } else {
                $listParams['where'][] = ['status', '=', $params['status']];
            }
        }
        $listParams['fields'] = ['id', 'uid', 'price', 'sn', 'status','add_time'];
        $listParams['order'] = [['field' => 'id', 'type' => 'desc']];
        $listParams['with'] = ['user'];

        $result = $this->getModelList(Orders::where('1=1'), $listParams);
        foreach($result['list'] as $key => $val) {
            $orderItems = [];
            $orderItemsRows = OrderItems::where('order_id', $val['id'])->select()->toArray();
            foreach ($orderItemsRows as $orKey => $orVal) {
                $productRow = StoreProduct::where('id', $orVal['product_id'])->find();
                $productAttrValueRow = StoreProductAttrValue::where([
                    ['product_id', '=', $orVal['product_id']],
                    ['unique', '=', $orVal['product_attr_value_unique']],
                ])->find();
                $orderItems[] = [
                    'id' => $orVal['id'],
                    'total_price' => $orVal['total_price'],
                    'fact_price' => $orVal['fact_price'],
                    'nums' => $orVal['nums'],
                    'store_name' => ($productRow) ? $productRow->store_name : '',
                    'image' => ($productAttrValueRow) ? $productAttrValueRow->image : '',
                    'suk' => ($productAttrValueRow) ? $productAttrValueRow->suk : '',
                ];
            }
            $result['list'][$key]['products'] = $orderItems;
            $result['list'][$key]['status_name'] = Orders::ORDER_STATUS_NAME[$val['status']];

        }

        return $result;
    }

    public function getOrderList($params){
        
        $listParams = [];
        if ($params['start_time'] && $params['end_time']) {
            $listParams['where'][] = ['Orders.add_time','>',$params['start_time']];
            $listParams['where'][] = ['Orders.add_time','<',$params['end_time']];
        }
        // 如果前端传递 -1, 则标识搜索全部，此时需要特殊处理
        if(isset($params['dstatus']) && $params['dstatus'] != -1) {
            $listParams['where'][] = ['Orders.status', '=', $params['dstatus']];
        }
        if(isset($params['sn']) && $params['sn'] != ''){
            $listParams['where'][] = ['Orders.sn', '=', $params['sn']];
        }
        if(isset($params['buyer_phone']) && $params['buyer_phone'] != ''){//买家电话
            $buyer = User::where('phone', $params['buyer_phone'])->find();
            if ($buyer) {
                $listParams['where'][] = ['Orders.uid', '=', $buyer->uid];
            }
        }
        if(isset($params['adder_phone']) && $params['adder_phone'] != ''){
            $listParams['where'][] = ['Orders.user_phone', '=', $params['adder_phone']];
        }
        if(isset($params['pay_type']) && $params['pay_type'] != 0){
            $listParams['where'][] = ['Orders.pay_type', '=', $params['pay_type']];
        }
        if(isset($params['distributor_id']) && $params['distributor_id'] != 0){//经销商   -1 是无经销商  0和空 是全部
            $distributor_id = $params['distributor_id'] == -1 ? 0 : $params['distributor_id'];
            $listParams['where'][] = ['Orders.distributor_id', '=', $distributor_id];
        }

        $query = Orders::hasWhere('orderItems')->with('orderItems');
        if($params['product_name'] != ''){
            $product = StoreProduct::where('store_name', $params['product_name'])->find();
            if(!empty($product)){
                $query = Orders::hasWhere('orderItems',['product_id'=>$product->id])->with(['orderItems']);
            }else{
                return [
                    'list' => [],
                    'total' => 0
                ];
            }
        }

        $listParams['fields'] = ['Orders.*'];
        $listParams['order'] = [['field' => 'id', 'type' => 'desc']];
        $result = $this->getModelList($query->where('Orders.is_del=0'), $listParams);
        foreach($result['list'] as $key => $val) {
            $orderItems = [];
            $result['list'][$key]['shipping_price'] = 0;
            foreach ($val['orderItems'] as $orKey => $orVal) {
                $productRow = StoreProduct::where('id', $orVal['product_id'])->find();
                if(empty($productRow)) continue;
                $productAttrValueRow = StoreProductAttrValue::where([
                    ['product_id', '=', $orVal['product_id']],
                    ['unique', '=', $orVal['product_attr_value_unique']],
                ])->find();

                $orderItems[] = [
                    'id' => $orVal['id'],
                    'total_price' => $orVal['total_price'],
                    'fact_price' => $orVal['fact_price'],
                    'nums' => $orVal['nums'],
                    'store_name' => $productRow->store_name,
                    'image' => $productAttrValueRow ? $productAttrValueRow->image : '',
                    'suk' => $productAttrValueRow ? $productAttrValueRow->suk : '',
                    'product_attr_value_unique' => $orVal['product_attr_value_unique'],
                    'remark' => $orVal['remark'],
                    'is_free' => $orVal['free_rule_uniques'] ? 1 : 0
                ];

                $result['list'][$key]['shipping_price'] += $orVal['shipping_price'];
            }
            unset($result['list'][$key]['orderItems']);
            $result['list'][$key]['products'] = $orderItems;
            $result['list'][$key]['distributor'] = '官方经销商';//经销商先写死
            $result['list'][$key]['add_time'] = date('Y-m-d H:i:s',$val['add_time']);
            $result['list'][$key]['status_name'] = Orders::ORDER_STATUS_NAME[$val['status']];
            $result['list'][$key]['pay_type_name'] = Orders::ORDER_PAY_TYPE_NAME[$val['pay_type']];
            $result['list'][$key]['sure_time'] = $val['sure_time'] ? date('Y-m-d H:i:s',$val['sure_time']) : '--';
            $result['list'][$key]['pay_time'] = $val['pay_time'] ? date('Y-m-d H:i:s',$val['pay_time']) : '--';
            $result['list'][$key]['cancel_time'] = $val['cancel_time'] ? date('Y-m-d H:i:s',$val['cancel_time']) : '--';
            $result['list'][$key]['shipping_time'] = $val['shipping_time'] ? date('Y-m-d H:i:s',$val['shipping_time']) : '--';

        }

        return $result;
    }

    /**
     * @param $params
     * @return array
     * 订单详情
     */
    public function detail($params)
    {
        $result = ['order' => [], 'guess_like' => []];
        $orderRow = $this->viewById(Orders::where('1=1'), $params['order_id']);
        if(!empty($orderRow)) {
            $orderItemsQuery = OrderItems::where('order_id', $params['order_id']);
            $result['order'] = [
                'id' => $orderRow['id'] ?? '',
                'sn' => $orderRow['sn'] ?? '',
                'status' => $orderRow['status'] ?? 0,
                'status_name' => Orders::ORDER_STATUS_NAME[$orderRow['status']] ?? '',
                'real_name' => $orderRow['real_name'],
                'user_phone' => $orderRow['user_phone'],
                'user_address' => $orderRow['user_address'] ?? '',
                'total_price' => $orderItemsQuery->sum('total_price'),
                'shipping_price' => $orderItemsQuery->sum('shipping_price'),
                'reduce_price' => $orderItemsQuery->sum('reduce_price'),
                'fact_price' => $orderItemsQuery->sum('fact_price'),
                'activity_price' => 0,//先写死,待完善
                'pay_time'  =>  date('Y-m-d H:i:s', $orderRow['pay_time']),
                'create_time' => date('Y-m-d H:i:s', $orderRow['add_time']),
                'pay_type' => $orderRow['pay_type'],
                'pay_type_name' => Orders::ORDER_PAY_TYPE_NAME[$orderRow['pay_type']],
                'shipping_time' => $orderRow['shipping_time'] ? date('Y-m-d H:i:s', $orderRow['shipping_time']) : '',
                'sure_time' => $orderRow['sure_time'] ? date('Y-m-d H:i:s', $orderRow['sure_time']) : '',
                'cancel_time' => $orderRow['cancel_time'] ? date('Y-m-d H:i:s', $orderRow['cancel_time']) : '',
                'remark' => $orderRow['remark'],
                'order_items' => [],
            ];
            $orderItemsRow = $orderItemsQuery->select()->toArray();
            foreach($orderItemsRow as $key => $val) {
                $productAttrValueRow = StoreProductAttrValue::where([
                    ['product_id', '=', $val['product_id']],
                    ['unique', '=', $val['product_attr_value_unique']],
                ])->find();
                $result['order']['order_items'][] = [
                    'id' => $val['id'],
                    'product_id'    =>  $val['product_id'],
                    'product_attr_value_unique' =>  $val['product_attr_value_unique'],
                    'nums' => $val['nums'],
                    'fact_price' =>  ($val['nums']) ? $val['fact_price'] / $val['nums'] : '0.00',
                    'image' => $productAttrValueRow->image ?? '',
                    'suk' => $productAttrValueRow->suk ?? '',
                    'store_name' => StoreProduct::where('id', $val['product_id'])->value('store_name'),
                ];
            }

            //获取猜你喜欢商品
            $result['guess_like'] = OrderTool::init()->getRandomProduct();
        }

        return $result;
    }

    /**
     * 订单发货
     * @param $params
     */
    public function shipping($params){

        foreach($params as $key => $val){
            if(empty($val) && $key != 'product_attr_value_unique'){
                throw new AdminException(60007);
            }
        }

        $where = ['order_id' => $params['order_id']];
        if(isset($params['product_attr_value_unique']) && !empty($params['product_attr_value_unique'])){
            $where['product_attr_value_unique'] = $params['product_attr_value_unique'];
        }

        Db::transaction(function () use ($where, $params) {

            OrderItems::where($where)->update([
                'shipping_time' => time(),
                'shipping_code' => $params['shipping_code'],
                'express_id' => $params['express_id'],
            ]);


            $orderItems = OrderItems::where($where)->select();
            foreach($orderItems as $orderItem){
                // 调整库存表
                InventoryTool::init()->inventory(request()->action(), $orderItem->product_id ?? 0, $orderItem->product_attr_value_unique ?? '', $orderItem->nums);
            }


            return Orders::where([
                'id' => $params['order_id']
            ])->update(['status' => 2]);
        });

    }

    /**
     * 售后备注
     * @param $params
     */
    public function remark($params){
        Db::transaction(function () use ($params) {
            OrderItems::where([
                'order_id' => $params['order_id'],
                'product_attr_value_unique' => $params['product_attr_value_unique']
            ])->update([
                'remark' => $params['remark']
            ]);
        });
    }

    /**
     * 卖家备注
     * @param $params
     */
    public function desc($params){
        Db::transaction(function () use ($params) {
            Orders::where([
                'id' => $params['order_id']
            ])->update([
                'order_desc' => $params['order_desc']
            ]);
        });
    }

    /**
     * @param $params
     * @return array
     * 物流查询（模拟）
     */
    public function viewLogistics($params)
    {
        $result = [
            'type' => '快递',
            'carrier' => '顺丰',
            'shipping_number' => 'SF1384814094393',
            'address' => '湖北省武汉市洪山区珞喻路100号',
            'logistics_data' => [],
        ];
        //模拟返回订单物流信息
        $apiUrl = 'http://www.kuaidi.com/index-ajaxselectcourierinfo--.html';
        $logistics = file_get_contents($apiUrl) ? json_decode(file_get_contents($apiUrl)) : [];
        if(!empty($logistics) && isset($logistics->success) && $logistics->success) {
            $result['logistics_data'] = $logistics->data;
        }

        return $result;
    }

    /**
     * @param $params
     * @return void
     * 确认收货
     */
    public function confirmReceipt($params)
    {
        Db::transaction(function () use ($params) {
            //修改订单状态为已完成
            Orders::where('id', $params['order_id'])->update(['status' => 3, 'sure_status' => 1, 'sure_time' => time()]);
            // 进入订单统计
            (new OrderMoneyStatisticService())->settleByOrderFinish($params['order_id']);

        });
    }

    /**
     * @param $params
     * @return void
     * 取消订单
     */
    public function cancel($params)
    {

        //修改订单状态为未支付
        $orderRow = OrderTool::init()->getOrder($params['order_id']);

        if(empty($orderRow)) {
            throw new ApiException(410173);
        }
        Db::transaction(function () use ($orderRow, $params) {

            $user_id = $orderRow['uid'];
            switch($orderRow['status']){
                case 0:
                    //待付款
                    OrderTool::init()->ordercancel($params['order_id'], $user_id);
                    //库存回滚
                    $orderItems = OrderItems::where('order_id', $params['order_id'])->select();
                    foreach ($orderItems as $orderItem) {
                        InventoryTool::init()->inventory('cancel', $orderItem->product_id ?? 0, $orderItem->product_attr_value_unique ?? '', $orderItem->nums);
                    }
                    break;
                case 1:
                    //待发货
                    //操作退款
                    OrderTool::init()->orderRefund($params['order_id'], $user_id);
                    //分销回滚
                    AgentTool::init()->agent(request()->action(), $params['order_id'], $user_id);
                    //库存回滚
                    $orderItems = OrderItems::where('order_id', $params['order_id'])->select();
                    foreach ($orderItems as $orderItem) {
                        InventoryTool::init()->inventory('refund', $orderItem->product_id ?? 0, $orderItem->product_attr_value_unique ?? '', $orderItem->nums);
                    }
                    break;
                case 2:
                    //待收货
                    throw new ApiException(60003);
                case 3:
                    //已完成
                    throw new ApiException(60004);
            }
        });
    }

    /**
     * @param $params
     * @return void
     * 软删除
     */
    public function delete($params)
    {
        Db::transaction(function () use ($params) {
            //软删除
            Orders::where('id', $params['order_id'])->where('uid', $params['user_id'])->update(['is_del' => 1]);
        });
    }

    /**
     * 查询订单
     * @param $params
     * @return array
     */
    public function queryOrder($params){

        return OrderTool::init()->getOrder($params['order_id'], $params['user_id']);
    }

    /**
     * 支付成功
     * 1.更新order表,status,pay_status,pay_sn,pay_time
     * @param $params
     */
    public function paySuccess($params){
        Orders::where('id',$params['order_id'])->update(
            [
                'status'=>1,
                'pay_status'=>1,
                'pay_sn' => $params['pay_sn'],
                'pay_time' => time()
            ]
        );
        //加入分销
        AgentTool::init()->agent('pay', $params['order_id'], $params['user_id']);
        $result = Orders::with(['orderItems'])->find($params['order_id'])->toArray();

        //修改库存
        foreach($result['orderItems'] as $val){
            $method = 'paySuccess';
            // 如果说，之前没有扣减库存的时候， 现在需要进行库存减少
            if ($val['has_deal_stock'] == 0) {
                InventoryTool::init()->inventory($method, $val['product_id'], $val['product_attr_value_unique'], $val['nums']);
            }
            // 当使用了优惠券的时候， 做去除库存逻辑
            if ($val['seckill_id']) {
                InventoryTool::init()->syncSeckillStock($method, $val);
            }
            // 当存在满赠的时候, 处理满赠库存
            if ($val['free_json']) {
                InventoryTool::init()->syncFreeStock($method, $val);
            }
        }
    }
}